'use strict'

let models = require('../models');
let errors = require('../../config/errors');

let School = models.School;
let Term = models.Term;
let Device = models.Device;

let SchoolDao = models.SchoolDao;
let TermDao = models.TermDao;
let DeviceDao = models.DeviceDao;

let festivalService = require('./festival');

function updateFestivals(school, festivalList) {
    // 剥离所有现有节日
    school.festivals.forEach(festival => {
        festivalService.detachFestival(festival);
    });

    // 创建新节日
    let festivals = festivalList.map(festivalItem => {
        let festival = festivalService.createFestival(festivalItem);
        festivalService.useFestival(festival);

        return festival;
    });

    // 重设节日
    let festivalIds = festivals.map(festival => festival.id);
    SchoolDao.update({
        id: school.id
    }, {
        $set: {
            festivals: festivalIds
        }
    });

    return festivals;
}

function getTimeSettings(schoolId) {
    let school = SchoolDao.findOne({
        id: schoolId
    });

    return {
        grades: school.grades.map(grade => {
            return {
                name: grade.name,
                checkTimeSet: grade.checkTimeSet
            };
        }),
        festivals: school.festivals,
        checkTimeSet: school.checkTimeSet
    };
}

function createTerm(school, termData) {
    let term = new Term(termData);

    TermDao.create(term);

    if ( school.terms == null ) {
        school.terms = [];
    }
    school.terms.push(term);
    SchoolDao.update(school);

    return term;
}

function updateTerm(term) {
    TermDao.update(term);

    return term;
}

function removeTerm(school,term) {
    SchoolDao.update({
        id: school.id
    }, {
        $pull: {
            terms: term.id
        }
    });

    TermDao.remove(term);
}

function getDeviceBySerialId(serialId) {
    return DeviceDao.findOne({
        serialId: serialId
    });
}

function getCurrentTerm(school) {
    let now = new Date();
    return school.terms.find(term => {
        return term.startTime <= now && now <= term.endTime;
    });
}

function getAllSchools() {
    return SchoolDao.find({});
}

module.exports = {
    getAllSchools,
    updateFestivals,
    getTimeSettings,
    createTerm,
    updateTerm,
    removeTerm,
    getCurrentTerm,
    getDeviceBySerialId
};
